package com.gitee.wsl.platform

import kotlinx.cinterop.*
import platform.posix.*

object LinuxNativePlatform:Platform{

    override val current: PlatformType
        get() = PlatformType.OS.Desktop.Linux(Arch.fromString(cpuArchitecture?:""),osVersion)

    override val fileSeparator: String
        get() = "/"

    override val lineSeparator: String
        get() = "\r\n"

    @OptIn(ExperimentalForeignApi::class)
    val utsName = memScoped {
        val utsName = alloc<platform.posix.utsname>()
        uname(utsName.ptr)

        // sysname = Name of this implementation of the operating system.
        val sysname = utsName.sysname.toKString() // utsName.sysname prints only nonsense after leaving memScoped

        utsName
    }

    // utsName.version = Current version level of this release, returned the date time of the build on my machine
    @OptIn(ExperimentalForeignApi::class)
    val osVersion: String = utsName.release.toKString() // Current release level of this implementation.

    @OptIn(ExperimentalForeignApi::class)
    fun getEnvironmentVariables(): Map<String, String> {
        val environmentVariables = mutableMapOf<String, String>()

        try {
            var environPointer = __environ // Start at the beginning of the environment block

            while (true) {
                val envEntryPointer = environPointer?.pointed?.value ?: break  // Stop if we reach the end (null entry)
                // Dereference to get the current entry

                val envEntry = envEntryPointer.toKString()
                val (key, value) = envEntry.split("=", limit = 2)
                environmentVariables[key] = value

                environPointer = environPointer.plus(1) // Move to the next entry
            }
        } catch (e: Throwable) {
            println("Could not get environment variables of Linux system: $e")
        }

        return environmentVariables
    }

    // utsName.machine == "x86_64", Platform.cpuArchitecture = "X64"
    @OptIn(ExperimentalForeignApi::class)
    val cpuArchitecture: String? = utsName.machine.toKString() // Name of the hardware type on which the system is running.
     //?: Platform.cpuArchitecture.name.lowercase()
}